<template>
  <div>
    <el-dialog :title="form.paper_id ? '编辑试卷' : '新增试卷'" style="width: 1000px;" modal-class="dialog-add"
      v-model="dialogVisible" @close="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false">
      <!--form表单-->
      <el-form size="small" ref="form" :model="form" :inline="true" :rules="formRules" :label-width="formLabelWidth">
        <el-row>
          <el-col :span="12">
            <el-form-item label="试卷类型" prop="category_id">
              <el-radio-group v-model="form.category_id" @input="radioSelect">
                <el-radio :label="9">随机出题</el-radio>
                <el-radio :label="12">固定出题</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职业" prop="career_id">
              <el-select size="small" style="width: 319px;" @change="careerChange" ref="career_id"
                v-model="form.career_id" placeholder="请选择">
                <el-option v-for="(item, index) in positionList" :key="index" :label="item.title"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="级别" prop="level_id">
              <el-select size="small" style="width: 319px;" @change="levelChange" ref="level_id" v-model="form.level_id"
                placeholder="请选择">
                <el-option v-for="(item, index) in levelList" :key="index" :label="item.title"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="方向" prop="direction_id">
              <el-select size="small" style="width: 319px;" @change="directionChange" ref="direction_id"
                v-model="form.direction_id" placeholder="请选择">
                <el-option v-for="(item, index) in directionList" :key="index" :label="item.title"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="试卷名称" prop="title"><el-input style="width: 319px;"
                v-model="form.title"></el-input></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时长" prop="exam_time"><el-input style="width: 319px;" v-model="form.exam_time"><template
                  #append>分钟</template></el-input></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总分"><el-input disabled style="width: 319px;"
                v-model="total_score"></el-input></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="及格" prop="passing_mark"><el-input style="width: 319px;"
                v-model="form.passing_mark"><template #append>分</template></el-input></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="良好" prop="good_score">
              <div style="display: flex; align-items: center;">
                <el-input style="width: 140px;" v-model="form.good_score"></el-input>
                <span>至</span>
                <el-input style="width: 140px;" v-model="form.good_score2"></el-input>
                <span>分</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优秀" prop="excellent_score">
              <div style="display: flex; align-items: center;">
                <el-input style="width: 140px;" v-model="form.excellent_score"></el-input>
                <span>至</span>
                <el-input style="width: 140px;" v-model="form.excellent_score2"></el-input>
                <span>分</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="display: flex">
        <div style="width: 10%; text-align: center; font-size: 12px; font-weight: 500;color: #333333;">规则</div>
        <table v-if="form.category_id == 9" class="table_one">
          <tr>
            <td>题目类型</td>
            <td>真题占比（%）</td>
            <td>题目数量</td>
            <td>每题得分</td>
          </tr>
          <tr>
            <td>单选</td>
            <td>
              <el-input style="width:90%" v-model="randomForm.single_percentage"></el-input>
            </td>
            <td>
              <el-input style="width:90%" v-model="randomForm.single_number"></el-input>
            </td>
            <td>
              <el-input style="width:90%" v-model="randomForm.single_score"></el-input>
            </td>
          </tr>
          <tr>
            <td>多选</td>
            <td>
              <el-input style="width:90%" v-model="randomForm.many_percentage"></el-input>
            </td>
            <td>
              <el-input style="width:90%" v-model="randomForm.many_number"></el-input>
            </td>
            <td>
              <el-input style="width:90%" v-model="randomForm.many_score"></el-input>
            </td>
          </tr>
          <tr>
            <td>判断</td>
            <td>
              <el-input style="width:90%" v-model="randomForm.judge_percentage"></el-input>
            </td>
            <td>
              <el-input style="width:90%" v-model="randomForm.judge_number"></el-input>
            </td>
            <td>
              <el-input style="width:90%" v-model="randomForm.judge_score"></el-input>
            </td>
          </tr>
        </table>
        <table v-if="form.category_id == 12" class="table_one table_two">
          <tr>
            <td>题目类型</td>
            <td>题目数量</td>
            <td>每题得分</td>
          </tr>
          <tr>
            <td>单选</td>
            <td>
              <el-input style="width:90%" v-model="fixedForm.single_number"></el-input>
            </td>
            <td>
              <el-input style="width:90%" v-model="fixedForm.single_score"></el-input>
            </td>
          </tr>
          <tr>
            <td>多选</td>
            <td>
              <el-input style="width:90%" v-model="fixedForm.many_number"></el-input>
            </td>
            <td>
              <el-input style="width:90%" v-model="fixedForm.many_score"></el-input>
            </td>
          </tr>
          <tr>
            <td>判断</td>
            <td>
              <el-input style="width:90%" v-model="fixedForm.judge_number"></el-input>
            </td>
            <td>
              <el-input style="width:90%" v-model="fixedForm.judge_score"></el-input>
            </td>
          </tr>
        </table>
      </div>
      <div style="display: flex" v-if="form.category_id == 12">
        <div style="width: 11%; text-align: center; font-size: 12px; font-weight: 500;color: #333333;">题目</div>
        <el-table size="small" style="width: 80%;" ref="dialogCrud0" max-height="500" :data="endData" border>
          <el-table-column width="160" align="center" show-overflow-tooltip prop="title" label="题目"></el-table-column>
          <el-table-column align="center" prop="category_id" label="题型">
            <template #default="scope">
              <span>{{ scope.row.type_name }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="100" align="center" prop="category_id" label="分类">
            <template #default="scope">
              <span>{{ scope.row.category_id == 1 ? '普通题' : scope.row.category_id === 3 ? '真题' : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" min-width="120">
            <template #default="scope">
              <el-button @click="deleteClick(scope.$index)" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="set_question" v-if="form.category_id == 12 && form.direction_id">
        <el-button type="primary" @click="onSearch(1, true)">出题</el-button>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit" :loading="loading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="固定出题" style="width: 1200px;" modal-class="dialog-add" v-model="dialogShow" @close="onClose"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <!--form表单-->
      <div class="box">
        <div class="box-l">
          <el-form size="small" :model="form" :inline="true" :rules="formRules">
            <el-row>
              <el-col :span="8">
                <el-form-item label="题型" prop="option_type">
                  <el-select size="small" style="width: 100px;" @change="typeChange"
                    v-model="treeSearchForm.option_type" placeholder="请选择">
                    <el-option v-for="(item, index) in optionList" :key="index" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="分类" prop="category_id">
                  <el-select size="small" style="width: 100px;" v-model="treeSearchForm.category_id" placeholder="请选择">
                    <el-option label="全部" :value="0"></el-option>
                    <el-option label="普通题" :value="1"></el-option>
                    <el-option label="真题" :value="3"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="role_id">
                  <el-button size="mini" type="primary" @click="onSearch(1)">查询</el-button>
                  <!-- <el-button size="mini" type="primary" @click="onJoinClick">加入</el-button> -->
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-table size="small" ref="dialogCrud" height="300" :data="dialogData" border v-loading="loading"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column width="160" align="center" show-overflow-tooltip prop="title" label="题目"></el-table-column>
            <el-table-column align="center" prop="category_id" label="题型">
              <template #default="scope">
                <span>{{ scope.row.type_name }}</span>
              </template>
            </el-table-column>
            <el-table-column min-width="100" align="center" prop="category_id" label="分类">
              <template #default="scope">
                <span>{{ scope.row.category_id == 1 ? '普通题' : scope.row.category_id === 3 ? '真题' : '' }}</span>
              </template>
            </el-table-column>
          </el-table>
          <!--分页-->
          <div class="pagination">
            <el-pagination @current-change="handleCurrentChange" background :current-page="curPage"
              :page-size="pageSize" layout="total, prev, pager, next, jumper" :total="totalDataNumber"></el-pagination>
          </div>
        </div>
        <div class="box-r">
          <el-form size="small" :model="form" :inline="true" :rules="formRules">
            <el-row>
              <el-col :span="8">
                <el-form-item label="题型" prop="option_type">
                  <el-select size="small" style="width: 100px;" v-model="selectSearchForm.question_type"
                    placeholder="请选择">
                    <el-option v-for="(item, index) in optionList" :key="index" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="分类" prop="category_id">
                  <el-select size="small" style="width: 100px;" v-model="selectSearchForm.category_id"
                    placeholder="请选择">
                    <el-option label="全部" :value="0"></el-option>
                    <el-option label="普通题" :value="1"></el-option>
                    <el-option label="真题" :value="3"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="role_id">
                  <el-button size="mini" type="primary" @click="onSearchSelect">查询</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="box-r-tip">
            <div class="box-r-tip-l">已选择{{ allNums.selectNum }}题/单选{{ allNums.danNum }}题/多选{{ allNums.duoNum }}题/判断{{
              allNums.panNum }}题</div>
            <div class="box-r-tip-r">待选择{{ total_number - allNums.selectNum }}题/单选{{ single_number -
              allNums.danNum }}题/多选{{ many_number - allNums.duoNum }}题/判断{{ judge_number -
                allNums.panNum }}题</div>
          </div>
          <div class="table_top">
            <el-table size="small" ref="dialogCrud2" height="300" :data="targetData" border>
              <el-table-column width="160" align="center" show-overflow-tooltip prop="title"
                label="题目"></el-table-column>
              <el-table-column align="center" prop="category_id" label="题型">
                <template #default="scope">
                  <span>{{ scope.row.type_name }}</span>
                </template>
              </el-table-column>
              <el-table-column min-width="100" align="center" prop="category_id" label="分类">
                <template #default="scope">
                  <span>{{ scope.row.category_id == 1 ? '普通题' : scope.row.category_id === 3 ? '真题' : '' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" fixed="right" label="操作" min-width="120">
                <template #default="scope">
                  <el-button @click="deleteItem(scope.row, scope.$index)" type="text" size="small">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onClose">取 消</el-button>
          <el-button type="primary" @click="addClick">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import ExaminationApi from '@/api/examination.js';
import PositionApi from '@/api/position.js';
import CourseApi from '@/api/course.js';
import { floatObj } from '@/utils/util.js';
import { isNumber200, isNumber1000, isValidNumber1000, isValidNumber100 } from '@/utils/validate.js'
import { ElMessage } from 'element-plus';
export default {
  data() {
    return {
      timer: '',
      radio: '1',
      /*左边长度*/
      formLabelWidth: '100px',
      /*是否显示*/
      loading: false,
      /*是否显示*/
      dialogVisible: true,
      positionList: [],
      levelList: [],
      directionList: [],
      /*form表单对象*/
      form: {
        paper_id: '',
        title: '',
        category_id: 9,
        career_id: '',
        level_id: '',
        direction_id: '',
        exam_time: '',
        passing_mark: '',
        good_score: '',
        good_score2: '',
        excellent_score: '',
        outline_id: ''
      },
      /*form验证*/
      formRules: {
        title: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          }
        ],
        category_id: [
          {
            required: true,
            message: ' ',
            trigger: 'change'
          },
        ],
        career_id: [
          {
            required: true,
            message: ' ',
            trigger: 'change'
          },
        ],
        level_id: [
          {
            required: true,
            message: ' ',
            trigger: 'change'
          },
        ],
        direction_id: [
          {
            required: true,
            message: ' ',
            trigger: 'change'
          },
        ],
        exam_time: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          }, {
            validator(rule, value, callback) {
              if (!isNumber1000(Number(value))) {
                callback(new Error('请输入正确的考试时长,时间范围为1-1000'));
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        passing_mark: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          },
          {
            validator(rule, value, callback) {
              if (!isValidNumber1000(value)) {
                callback(new Error('请输入正确的及格分数,分数范围为0-1000'));
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        good_score: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          },
          {
            validator(rule, value, callback) {
              if (!isValidNumber1000(value)) {
                callback(new Error('请输入正确的良好分数,分数范围为0-1000'));
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        excellent_score: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          },
          {
            validator(rule, value, callback) {
              if (!isValidNumber1000(value)) {
                callback(new Error('请输入正确的优秀分数,分数范围为0-1000'));
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
      },
      // 搜索题目
      treeSearchForm: {
        option_type: 0,
        category_id: 0,
      },
      selectSearchForm: {
        question_type: 0,
        category_id: 0,
      },
      // 列表数据
      optionList: [
        {
          label: '全部',
          value: 0
        },
        {
          label: '单选',
          value: 1
        },
        {
          label: '多选',
          value: 2
        },
        {
          label: '判断',
          value: 3
        }
      ],
      treeData: [],
      lastCheckedKey: '',
      tableData: [],
      tableDataSelect: [],
      targetData: [],
      targetDataSelect: [],
      danNum: 0, // 已选择的单选题目数
      duoNum: 0, // 已选择的多选题目数
      panNum: 0, // 已选择的判断题目数
      dialogShow: false,
      /*当前是第几页*/
      curPage: 1,
      /*一页多少条*/
      pageSize: 10,
      /*一共多少条数据*/
      totalDataNumber: 0,
      endData: [],
      dialogData: [],
      flag: false,
      randomForm: {
        single_percentage: '',
        many_percentage: '',
        judge_percentage: '',
        single_number: '',
        many_number: '',
        judge_number: '',
        single_score: '',
        many_score: '',
        judge_score: '',
      },
      fixedForm: {
        single_number: '',
        many_number: '',
        judge_number: '',
        single_score: '',
        many_score: '',
        judge_score: '',
      }
    };
  },
  mounted() {
  },
  created() {
    this.getPositionAll()
  },
  computed: {
    allNums() {
      let selectNum = 0
      let danNum = 0
      let duoNum = 0
      let panNum = 0
      this.targetData.forEach(item => {
        selectNum++
        if (item.question_type === 1) {
          danNum++
        } else if (item.question_type === 2) {
          duoNum++
        } else {
          panNum++
        }
      })
      return {
        selectNum,
        danNum,
        duoNum,
        panNum
      }
    },
    allNums2() {
      let selectNum = 0
      let danNum = 0
      let duoNum = 0
      let panNum = 0
      this.endData.forEach(item => {
        selectNum++
        if (item.question_type === 1) {
          danNum++
        } else if (item.question_type === 2) {
          duoNum++
        } else {
          panNum++
        }
      })
      return {
        selectNum,
        danNum,
        duoNum,
        panNum
      }
    },
    total_score() {
      let values = 0
      let key = 'randomForm'
      if (this.form.category_id != 9) {
        key = 'fixedForm'
      }
      const singleAllScore = floatObj(this[key].single_number, this[key].single_score, 'multiply')
      const manyAllScore = floatObj(this[key].many_number, this[key].many_score, 'multiply')
      const judgeAllScore = floatObj(this[key].judge_number, this[key].judge_score, 'multiply')
      values = floatObj(floatObj(singleAllScore, manyAllScore, 'add'), judgeAllScore, 'add')
      return values
    },
    total_number() {
      let key = 'randomForm'
      if (this.form.category_id != 9) {
        key = 'fixedForm'
      }
      return floatObj(floatObj(this[key].single_number, this[key].many_number, 'add'), this[key].judge_number, 'add')
    },
    single_number() {
      let key = 'randomForm'
      if (this.form.category_id != 9) {
        key = 'fixedForm'
      }
      return this[key].single_number || 0
    },
    many_number() {
      let key = 'randomForm'
      if (this.form.category_id != 9) {
        key = 'fixedForm'
      }
      return this[key].many_number || 0
    },
    judge_number() {
      let key = 'randomForm'
      if (this.form.category_id != 9) {
        key = 'fixedForm'
      }
      return this[key].judge_number || 0
    },
  },
  methods: {
    getEdittrainPaper() {
      let self = this;
      ExaminationApi.getEdittrainPaper({
        paper_id: self.form.paper_id,
        scene: 'edit'
      },
        true
      )
        .then(res => {
          console.log(res.data.model.question, 'res.data.model')
          if (res.data && res.data.model && res.data.model.question) {
            this.endData = []
            res.data.model.question && res.data.model.question.map(item => {
              if (item.question) {
                item.question.paper_question_id = item.paper_question_id
                this.endData.push(item.question)
              }
            })
          }
        })
        .catch(error => {
          self.loading = false;
        });
    },
    deleteClick(index) {
      this.endData.splice(index, 1)
    },
    addClick() {
      this.endData = this.targetData
      this.dialogShow = false
    },    // 防抖函数
    deBounce(fn, delay, list) {
      const myDeBounce = () => {
        if (this.timer) clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          fn(list);
          this.timer = null;
        }, delay);
      };
      return myDeBounce;
    },
    filterList(list) {
      this.dialogData.forEach((item) => {
        // 如果list中没有该条数据，就进行删除操作，如果list中有该条数据，就进行push操作
        if (list.findIndex((i) => i.question_id === item.question_id) === -1) {
          // 不满足进行过滤操作
          this.targetData = this.targetData.filter(
            (items) => item.question_id !== items.question_id
          );
        } else {
          // 满足先进行判断原有数组中的该条数据，如果不存在则进行push操作，存在则不做操作
          if (
            this.targetData.findIndex((i) => i.question_id === item.question_id) === -1
          ) {
            this.targetData.push(item);
          }
        }
      });
    },
    getPositionAll() {
      PositionApi.getNestedData({}, true)
        .then(res => {
          this.positionList = res.data;
          if (this.form.career_id) {
            this.getLevelAll()
          }
        })
        .catch(error => { });
    },
    careerChange() {
      this.form.level_id = ''
      this.levelList = []
      this.form.level_title = ''
      this.getLevelAll()
      this.form.direction_id = ''
      this.directionList = []
      this.form.direction_title = ''
      this.form.outline_id = ''
    },
    getLevelAll() {
      PositionApi.getCareerLevel({
        career_id: this.form.career_id
      }, true)
        .then(data => {
          this.levelList = data.data;
          if (this.form.level_id) {
            this.getDirectionAll()
          }
        })
        .catch(error => { });
    },
    levelChange() {
      this.form.direction_id = ''
      this.directionList = []
      this.form.direction_title = ''
      this.form.outline_id = ''
      this.getDirectionAll()
    },
    getDirectionAll() {
      PositionApi.getCareerDirection({
        career_id: this.form.career_id,
        level_id: this.form.level_id
      }, true)
        .then(data => {
          this.directionList = data.data;
        })
        .catch(error => { });
    },
    directionChange() {
      this.form.outline_id = ''
      this.getTreeList()
    },
    getTreeList() {
      let self = this;
      let Params = {
        career_id: this.form.career_id,
        level_id: this.form.level_id,
        direction_id: this.form.direction_id
      };
      CourseApi.getNestedData(Params, true)
        .then(data => {
          self.loading = false;
          self.treeData = data.data;
          self.treeData && self.treeData.map(item => {
            item.parent_id = 0
            item.disabled = true
            item.children && item.children.map(childrenItem => {
              childrenItem.parent_id = item.id
              childrenItem.disabled = true
              childrenItem.children && childrenItem.children.map(grandsonItem => {
                grandsonItem.ids = item.id
                grandsonItem.parent_id = childrenItem.id
                return grandsonItem
              })
              return childrenItem
            })
            return item
          })
        })
        .catch(error => { });
    },
    // 勾选节点
    handleCheck(node, checked) {
      console.log(node, checked, '123123')
      if (this.lastCheckedKey && this.lastCheckedKey !== node.id) {
        this.$refs.tree.setChecked(this.lastCheckedKey, false);
      }
      this.lastCheckedKey = node.id;
      if (checked.checkedKeys && checked.checkedKeys.length) {
        this.form.outline_id = node.id
      } else {
        this.form.outline_id = ''
      }
    },
    // 编辑回显
    setTitle(row) {
      console.log(row, 'row')
      this.form.paper_id = row.paper_id
      this.form.category_id = row.category_id
      this.form.career_id = row.career_id
      this.form.level_id = row.level_id
      this.form.direction_id = row.direction_id
      this.form.title = row.title
      this.form.exam_time = row.exam_time
      this.total_score = row.total_score
      this.form.passing_mark = row.passing_mark
      const good_score = row.good_score.split('-')
      this.form.good_score = good_score[0]
      this.form.good_score2 = good_score[1]
      const excellent_score = row.excellent_score.split('-')
      this.form.excellent_score = excellent_score[0]
      this.form.excellent_score2 = excellent_score[1]
      if (this.form.category_id == 9) {
        this.randomForm.single_number = row.single_number
        this.randomForm.many_number = row.many_number
        this.randomForm.judge_number = row.judge_number
        this.randomForm.single_score = row.single_score
        this.randomForm.many_score = row.many_score
        this.randomForm.judge_score = row.judge_score
        this.randomForm.single_percentage = row.single_percentage
        this.randomForm.many_percentage = row.many_percentage
        this.randomForm.judge_percentage = row.judge_percentage
      } else {
        this.fixedForm.single_number = row.single_number
        this.fixedForm.many_number = row.many_number
        this.fixedForm.judge_number = row.judge_number
        this.fixedForm.single_score = row.single_score
        this.fixedForm.many_score = row.many_score
        this.fixedForm.judge_score = row.judge_score
      }
      this.endData = []
      if (this.form.paper_id) {
        this.getEdittrainPaper()
      }
    },
    /*添加*/
    onSubmit() {
      let keys = 'randomForm'
      if (this.form.category_id != 9) {
        keys = 'fixedForm'
      } else {
        if (!isValidNumber100(this[keys].single_percentage) || this[keys].single_percentage > 100 || !isValidNumber100(this[keys].many_percentage) || this[keys].many_percentage > 100 || !isValidNumber100(this[keys].judge_percentage) || this[keys].judge_percentage > 100) {
          ElMessage({
            message: '请输入正确的真题占比',
            type: 'error'
          })
          return false
        }
      }
      if (!isNumber200(this[keys].single_number) || !isNumber200(this[keys].many_number) || !isNumber200(this[keys].judge_number)) {
        ElMessage({
          message: '请输入正确的题目数量',
          type: 'error'
        })
        return false
      }
      if (!this[keys].single_score || !isValidNumber1000(this[keys].single_score) || !this[keys].many_score || !isValidNumber1000(this[keys].many_score) || !this[keys].judge_score || !isValidNumber1000(this[keys].judge_score)) {
        ElMessage({
          message: '请输入正确的的题目分数',
          type: 'error'
        })
        return false
      }
      if (!this.form.good_score || !isValidNumber1000(this.form.good_score) || !this.form.good_score2 || !isValidNumber1000(this.form.good_score2) || Number(this.form.good_score2) < Number(this.form.good_score)) {
        ElMessage({
          message: '请输入正确的良好分数',
          type: 'error'
        })
        return false
      }
      if (!this.form.excellent_score || !isValidNumber1000(this.form.excellent_score) || !this.form.excellent_score2 || !isValidNumber1000(this.form.excellent_score2) || Number(this.form.excellent_score2) < Number(this.form.excellent_score)) {
        ElMessage({
          message: '请输入正确的优秀分数',
          type: 'error'
        })
        return false
      }
      if (!this.form.passing_mark || !isValidNumber1000(this.form.passing_mark) || Number(this.form.passing_mark) >= Number(this.form.good_score)) {
        ElMessage({
          message: '请输入正确的及格分数',
          type: 'error'
        })
        return false
      }
      if (Number(this.form.good_score2) >= Number(this.form.excellent_score)) {
        ElMessage({
          message: '请输入正确的良好分数',
          type: 'error'
        })
        return false
      }
      if (Number(this.form.excellent_score2) > Number(this.form.total_score)) {
        ElMessage({
          message: '请输入正确的优秀分数',
          type: 'error'
        })
        return false
      }
      if (this.form.category_id != 9) {
        console.log(this.allNums2,'this.allNums2')
        if (Number(this.single_number) != Number(this.allNums2.danNum)) {
          ElMessage({
            message: '请按规则选择单选题数',
            type: 'error'
          })
          return false
        }
        if (Number(this.many_number) != Number(this.allNums2.duoNum)) {
          ElMessage({
            message: '请按规则选择多选题数',
            type: 'error'
          })
          return false
        }
        if (Number(this.judge_number) != Number(this.allNums2.panNum)) {
          ElMessage({
            message: '请按规则选择判断题数',
            type: 'error'
          })
          return false
        }
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          let self = this;
          self.loading = true;
          let params;
          if (this.form.category_id == 9) {
            params = {
              ...this.randomForm
            }
          } else {
            params = {
              ...this.fixedForm
            }
          }
          let key = 'addExamination'
          let msg = '新增成功'
          if (self.form.paper_id) {
            key = 'editExamination'
            msg = '编辑成功'
            params.paper_id = self.form.paper_id,
              params.scene = 'edit'
          }
          params.career_id = this.form.career_id
          params.level_id = this.form.level_id
          params.direction_id = this.form.direction_id
          params.category_id = this.form.category_id
          params.exam_time = this.form.exam_time
          params.passing_mark = this.form.passing_mark
          params.good_score = this.form.good_score + '-' + this.form.good_score2
          params.excellent_score = this.form.excellent_score + '-' + this.form.excellent_score2
          params.paper_question_id = 0
          params.title = this.form.title
          params.image_id = 10833
          params.item_number = floatObj(floatObj(params.single_number, params.many_number, 'add'), params.judge_number, 'add')
          params.virtual_answer = 0
          params.total_score = this.total_score
          params.difficulty = 5
          params.sort = 0
          params.is_score = 0
          params.is_show = 0
          params.virtual_sales = 0
          params.question = []
          params.single = []
          params.many = []
          params.judge = []
          params.career_title = this.$refs.career_id.selectedLabel
          params.level_title = this.$refs.level_id.selectedLabel
          params.direction_title = this.$refs.direction_id.selectedLabel
          if (this.form.category_id === 12) {
            if (!this.endData || !this.endData.length) {
              ElMessage({
                message: '请选择试题',
                type: 'error'
              });
              return false
            }
            let question = []
            let single = []
            let many = []
            let judge = []
            this.endData.forEach(item => {
              question.push(item)
              if (item.question_type == 1) {
                single.push(item)
              } else if (item.question_type == 2) {
                judge.push(item)
              } else if (item.question_type == 3) {
                many.push(item)
              }
            })
            params.question = question
            params.single = single
            params.many = many
            params.judge = judge
          }
          ExaminationApi[key]({ params: JSON.stringify(params) }, true)
            .then(data => {
              self.loading = false;
              ElMessage({
                message: msg,
                type: 'success'
              });
              self.dialogFormVisible(true);
            })
            .catch(error => {
              self.loading = false;
            });
        } else {
          console.log('error submit!!')
        }
      })
    },
    /*关闭弹窗*/
    dialogFormVisible(e) {
      if (e) {
        this.$emit('close', {
          type: 'success',
          openDialog: false
        });
      } else {
        this.$emit('close', {
          type: 'error',
          openDialog: false
        });
      }
    },

    // 试题类型选择
    radioSelect(e) {
      if (e.target.value == 9) {
        // 清除固定出题数据
        this.clearData()
      }
    },
    // 获取所有题目数量
    getQuestionStatistics() {
      CourseApi.getQuestionStatistics({}).then(res => {
        if (res.code == 1) {
          this.allNum = res.data
        }
      })
    },
    // 查询试题
    onSearch(val = '', type = false) {
      if (val) {
        this.curPage = val
      }
      if (type) {
        this.targetData = [...this.endData]
      }
      this.dialogShow = true
      let self = this;
      let Params = {
        page: this.curPage,
        list_rows: this.pageSize,
        category_id: this.treeSearchForm.category_id,
        question_type: this.treeSearchForm.option_type,
      };
      Params.career_id = this.form.career_id
      Params.level_id = this.form.level_id
      Params.direction_id = this.form.direction_id
      CourseApi.getQuestionList(Params, true).then(res => {
        self.loading = false;
        if (res.code == 1) {
          self.dialogData = res.data.list.data;
          self.totalDataNumber = res.data.list.total;
          this.$nextTick(() => {
            this.flag = true;
            try {
              this.$refs.dialogCrud.clearSelection();
            } catch (error) {
              console.log(error);
            }
            this.$nextTick(() => {
              const arrlist = this.targetData;
              const targetList = [];
              this.dialogData.forEach((item) => {
                arrlist.forEach((i) => {
                  if (item.question_id === i.question_id) {
                    targetList.push(item);
                  }
                });
              });
              if (targetList && targetList.length) {
                targetList.forEach(item => {
                  this.$refs.dialogCrud.toggleRowSelection(item, undefined, true);
                })
              } else {
                this.flag = false;
              }
            });
          });
        }
      })
        .catch(error => { });
    },

    // 左侧选择试题
    handleSelectionChange(list = []) {
      if (!this.flag) {
        this.deBounce(this.filterList, 0, list)();
      }
      this.flag = false;
    },
    deleteItem(row, index) {
      let targetRow = ''
      this.dialogData && this.dialogData.forEach(item => {
        if (item.question_id == row.question_id) {
          targetRow = item
        }
      })
      if (targetRow) {
        this.$refs.dialogCrud.toggleRowSelection(targetRow, false);
      } else {
        this.targetData.splice(index, 1)
      }
    },
    /*选择第几页*/
    handleCurrentChange(val) {
      let self = this;
      self.curPage = val;
      self.onSearch();
    },
    // 查询已选择的试题
    onSearchSelect() {
      let arr = JSON.parse(localStorage.getItem('targetData'))
      if (this.selectSearchForm.question_type == 0 && this.selectSearchForm.category_id == 0) {
        this.targetData = arr
      } else if (this.selectSearchForm.question_type == 0 && this.selectSearchForm.category_id !== 0) {
        this.targetData = arr.filter(item => item.category_id == this.selectSearchForm.category_id);
      } else if (this.selectSearchForm.question_type !== 0 && this.selectSearchForm.category_id == 0) {
        this.targetData = arr.filter(item => item.question_type == this.selectSearchForm.question_type);
      } else {
        this.targetData = arr.filter(item => item.question_type == this.selectSearchForm.question_type && item.category_id == this.selectSearchForm.category_id);
      }
    },
    // 关闭固定出题弹窗
    onClose() {
      this.dialogShow = false
    },
    // 清除固定出题数据
    clearData() {
      this.tableData = []
      this.tableDataSelect = []
      this.targetDataSelect = []
      this.targetData = []
      this.selectNum = 0 // 已选择题目数
      this.danNum = 0 // 已选择的单选题目数
      this.duoNum = 0 // 已选择的多选题目数
      this.panNum = 0 // 已选择的判断题目数
      localStorage.clear('targetData')
    }
  }
};
</script>

<style scoped>
.table_one {
  width: 85%;
  margin-bottom: 20px;
}

table {
  border-top: 1px solid #DCDCDC;
  border-left: 1px solid #DCDCDC;
  border-spacing: 0;
  /*去掉单元格间隙*/
}

table td {
  width: 33%;
  padding: 5px 0;
  text-align: center;
  border-bottom: 1px solid #DCDCDC;
  border-right: 1px solid #DCDCDC;
}

.table_one td {
  width: 25%;
}

.set_question {
  width: 100%;
  display: flex;
  padding: 0 40px;
}

.box {
  width: 100%;
  height: 70vh;
  display: flex;
}

.box-l {
  width: 50%;
  padding: 0 10px;
}

.box-r {
  flex: 1;
  width: 50%;
  padding: 0 10px;
  border-left: 1px solid #EEEEEE;
}

.box-r-tip {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  margin-bottom: 10px;
}

.box-r-tip-l {
  width: 50%;
  color: #0158FD
}

.box-r-tip-r {
  width: 50%;
  color: #FF9900
}

.box-r-head {
  height: 30px;
  line-height: 30px;
  margin-top: 10px;
  font-size: 12px;
  text-align: center;
  background: #f5f5f5;
}


.table_top {
  width: 100%;
  height: 495px;
  overflow-y: scroll;
}

::v-deep .el-table {
  overflow: visible;
}

::v-deep .el-table__header-wrapper {
  position: sticky;
  top: 0px;
  z-index: 10;
}


.el-button {
  width: 50px !important;
}

::v-deep .el-tree .el-tree-node__content {
  padding: 3px 0;
}

/* 覆盖被选中节点的字体颜色 */
::v-deep .el-tree .el-tree-node__content:hover {
  color: #409EFF;
  /* 更改为你想要的颜色 */
  background: rgba(229, 238, 255, 1);
}

::v-deep .el-tree-node:focus>.el-tree-node__content {
  color: #409EFF !important;
  background: rgba(229, 238, 255, 1);
}
</style>
